package com.haocang.szgm.ui.waterpoint.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.event.OnSingleTapListener;
import com.esri.core.geometry.Point;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.PictureMarkerSymbol;
import com.haocang.commonlib.gismap.MapUtils;
import com.haocang.szgm.R;
import com.haocang.szgm.activity.comm.CommMapFinalActivity;
import com.haocang.szgm.activity.tool.CacheActivityUtil;
import com.haocang.szgm.requestcenter.DataModel;
import com.haocang.commonlib.network.interfaces.InitDataBeanBack;
import com.haocang.szgm.ui.waterpoint.adapter.WaterPointListAdapter;
import com.haocang.szgm.ui.waterpoint.bean.WaterPointBean;
import com.haocang.szgm.ui.waterpoint.utils.ComputeTools;
import com.haocang.szgm.utils.bean.ProvinceBean;
import com.haocang.szgm.utils.config.Config;
import com.haocang.szgm.utils.config.WebApi;
import com.haocang.commonlib.recyclerView.BaseAdapter;
import com.haocang.szgm.utils.tools.CacheData;
import com.haocang.szgm.utils.tools.MyTextUtils;
import com.haocang.szgm.utils.tools.OptionsItemsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import net.tsz.afinal.annotation.view.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WaterPointActivity extends CommMapFinalActivity {

    @ViewInject(id = R.id.tv_map_addpoint)
    TextView tv_map_addpoint;

    @ViewInject(id = R.id.map_lin)
    RelativeLayout map_lin;
    @ViewInject(id = R.id.list)
    LinearLayout list;

    @ViewInject(id = R.id.et_year)
    EditText et_year;
    @ViewInject(id = R.id.tv_status)
    TextView tv_status;
    @ViewInject(id = R.id.tv_reason)
    TextView tv_reason;
    @ViewInject(id = R.id.bt_quert)
    Button bt_quert;
    @ViewInject(id = R.id.list_quert_lin)
    LinearLayout list_quert_lin;

    @ViewInject(id = R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @ViewInject(id = R.id.recyclerview)
    RecyclerView recyclerview;

    @ViewInject(id = R.id.water_tj_a) TextView water_tj_a;
    @ViewInject(id = R.id.water_tj_b) TextView water_tj_b;
    @ViewInject(id = R.id.water_tj_c) TextView water_tj_c;
    @ViewInject(id = R.id.water_tj_d) TextView water_tj_d;
    @ViewInject(id = R.id.water_tj_e) TextView water_tj_e;
    @ViewInject(id = R.id.water_tj_f) TextView water_tj_f;
    @ViewInject(id = R.id.water_tj_g) TextView water_tj_g;
    private WaterPointListAdapter mAdapter;
    protected GraphicsLayer gWaterLayer;//自定义图层
    private Map<Integer, WaterPointBean> mLocationMapList;

    private String TYPE = "";
    private Context context;


    @ViewInject(id = R.id.tv_map_legend)
    LinearLayout tv_map_legend;
    @ViewInject(id = R.id.lin_legend)
    LinearLayout lin_legend;
    @ViewInject(id = R.id.tv_map_lable)
    LinearLayout tv_map_lable;
    @ViewInject(id = R.id.iv_tuli_close)
    ImageView tv_close;

    private List<WaterPointBean> waterlist = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CacheActivityUtil.addActivity(WaterPointActivity.this);
        context = this;
        initView();

        initEvent();

        initMyLocation();

        refreshLayout.autoRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (refreshLayout != null) {
            refreshLayout.autoRefresh();
        }
        gLayerPos.removeAll();
        SingleTap_X = 0 ;
        SingleTap_Y = 0;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CacheActivityUtil.finishSingleActivity(WaterPointActivity.this);
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_water_point;
    }

    @Override
    protected boolean showNavigation() {
        return true;
    }

    @Override
    protected boolean showMedia() {
        return false;
    }

    @Override
    protected int showMoreIcon() {
        return R.drawable.ic_list;
    }

    @Override
    protected String showTitleName() {
        return "积水监测";
    }

    @Override
    protected boolean showMapPipe() {
        return false;
    }

    private void initView() {

        IsLable = false;

        Intent it = getIntent();
        TYPE = it.getStringExtra("TYPE");

        if (TYPE.equals("NOW")) {
            map_lin.setVisibility(View.VISIBLE);
            list.setVisibility(View.GONE);
            tv_name.setText("积水监测");
            et_year.setVisibility(View.GONE);
            tv_reason.setVisibility(View.GONE);
            iv_more_icon.setBackgroundResource(R.drawable.ic_list);
        } else if (TYPE.equals("OLD")) {
            map_lin.setVisibility(View.GONE);
            list.setVisibility(View.VISIBLE);
            tv_name.setText("历史积水点");
            et_year.setVisibility(View.VISIBLE);
            tv_reason.setVisibility(View.VISIBLE);
            iv_more_icon.setBackgroundResource(R.drawable.ic_map);
        }

        gWaterLayer = new GraphicsLayer();
        mMapView.addLayer(gWaterLayer);

        mLocationMapList = new HashMap<>();
        mAdapter = new WaterPointListAdapter(WaterPointActivity.this);
        recyclerview.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) {
            @Override
            public boolean canScrollVertically() {
                return true;//是否允许滑动
            }
        });
        recyclerview.setAdapter(mAdapter);
    }

    private void initEvent() {

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        });

        tv_map_mylocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CacheData.Cache_MyLocation != null){
                    initMyLocation();
                   // mMapView.centerAt(new Point(CacheData.Cache_MyLocation.getX(),CacheData.Cache_MyLocation.getX()),true);
                }else{
                    ToastShow("当前GPS未获取到位置，请稍后重试！");
                }
            }
        });

        iv_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (list.getVisibility() == View.GONE) {
                    list.setVisibility(View.VISIBLE);
                    map_lin.setVisibility(View.GONE);
                    list.setAnimation(AnimationUtils.makeInAnimation(mContext, true));
                    map_lin.setAnimation(AnimationUtils.makeOutAnimation(mContext, true));
                    iv_more_icon.setBackgroundResource(R.drawable.ic_map);
                } else {
                    list.setVisibility(View.GONE);
                    map_lin.setVisibility(View.VISIBLE);
                    list.setAnimation(AnimationUtils.makeOutAnimation(mContext, false));
                    map_lin.setAnimation(AnimationUtils.makeInAnimation(mContext, false));
                    iv_more_icon.setBackgroundResource(R.drawable.ic_list);
                }
            }

        });

        mMapView.setOnSingleTapListener(new OnSingleTapListener() {
            @Override
            public void onSingleTap(float x, float y) {

                int[] ids = gWaterLayer.getGraphicIDs(x, y, 5);
                if (ids.length > 0) {
                    final WaterPointBean bean = mLocationMapList.get(ids[0]);

                    if(bean.getIsDelete().equals("Y")){
                        Intent intent = new Intent(context, SureWaterPointActivity.class);
                        intent.putExtra("ID",bean.getID());
                        startActivity(intent);
                    }else if(bean.getIsDelete().equals("N")){
                        Intent intent = new Intent(context, SureWaterPointActivity.class);
                        intent.putExtra("ID",bean.getID());
                        startActivity(intent);
                    }else if(bean.getIsDelete().equals("S")) {
                        CacheData.WaterPoint_UPDATE = true;
                        CacheData.mWaterPointID = bean.getID();
                        Intent it = new Intent(context, WaterPointDetailActivity.class);
                        startActivity(it);
                    }

                } else {

                    Point mapPoint = mMapView.toMapPoint(x, y);
                    SingleTap_X = mapPoint.getX();
                    SingleTap_Y = mapPoint.getY();
                    addpoint(mapPoint, R.mipmap.jsd_add);
                }
            }
        });


        tv_map_addpoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SingleTap_X == 0 || SingleTap_Y == 0) {
                    ToastShow("请在地图上设置积水位置");
                    return;
                }
                //跳转到积水明细上报界面
                CacheData.WaterPoint_UPDATE = false;
                CacheData.mWaterPointID = "";
                Intent intent = new Intent(WaterPointActivity.this, WaterPointAddActivity.class);
                intent.putExtra("X", SingleTap_X);
                intent.putExtra("Y", SingleTap_Y);
                startActivity(intent);
            }
        });


        tv_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDeviceCode(OptionsItemsUtils.GetAllWaterPointStatus(), 1);
            }

        });

        tv_reason.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseDeviceCode(OptionsItemsUtils.GetOldAllReasonList(), 2);
            }

        });
        bt_quert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshLayout.autoRefresh();
            }

        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                Config.PAGE_LIMIT = Config.PAGE_SHOW_LIMIT;
                refreshlayout.finishRefresh(20000/*,false*/);//传入false表示刷新失败
                initData(refreshlayout);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore(20000/*,false*/);//传入false表示加载失败
                Config.PAGE_LIMIT += Config.PAGE_SHOW_LIMIT;
                initData(refreshlayout);
            }
        });

        mAdapter.setOnItemChildClickListener(new BaseAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseAdapter adapter, View v, int position) {
                WaterPointBean model = mAdapter.getItem(position);
                Intent intent = new Intent(WaterPointActivity.this, WaterPointDetailActivity.class);
                CacheData.WaterPoint_UPDATE = true;
                CacheData.mWaterPointID = model.getID();
                startActivity(intent);
            }

        });

        tv_map_legend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lin_legend.getVisibility() == View.VISIBLE) {
                    lin_legend.setVisibility(View.GONE);
                } else {
                    lin_legend.setVisibility(View.VISIBLE);
                }
            }
        });

        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lin_legend.setVisibility(View.GONE);
            }
        });


        tv_map_lable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (IsLable) {
                    IsLable = false;
                } else {
                    IsLable = true;
                }
                MarkWaterPoint(waterlist);

            }
        });

    }

    private void initData(final RefreshLayout refreshlayout) {
        if (TYPE.equals("NOW")) {
            initNowData(refreshlayout);
        } else if (TYPE.equals("OLD")) {
            initOldData(refreshlayout);
        }
    }

    private void initNowData(final RefreshLayout refreshlayout) {


        String status = MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetAllWaterPointStatus(), 0, tv_status.getText().toString());

        //获取当前的预警行动的积水点
        String ApiUrl = Config.host
                + WebApi.Api_WaterPoint
                + "?limit=1000"
                + "&status=" + status
                + "&WarningID=" + CacheData.Cache_WaringID;

       // String ApiUrl =   Config.host + WebApi.Api_GetWaterPointList;

        DataModel.GetApiRequestMode("WaterPointBean", ApiUrl, new InitDataBeanBack<WaterPointBean>() {
            @Override
            public void callbak(boolean b, List<WaterPointBean> list, String msg) {
                if (b) {


                    waterlist = list;

                    mAdapter.setNewData(list);

                    MarkWaterPoint(list);
                    if (list.size() == 0) {
                        ToastShow("当前无积水点！");
                    }
                    refreshlayout.finishRefresh(true);//刷新完成
                    refreshlayout.finishLoadmore(true);

                    String[] nubber_arr =  ComputeTools.StatisticsWaterNumber(list);
                    water_tj_a.setText(nubber_arr[0]);
                    water_tj_b.setText(nubber_arr[1]);
                    water_tj_c.setText(nubber_arr[2]);
                    water_tj_d.setText(nubber_arr[3]);
                    water_tj_e.setText(nubber_arr[4]);
                    water_tj_f.setText(nubber_arr[5]);
                    water_tj_g.setText(nubber_arr[6]);
                } else {
                    ToastShow(msg);
                    refreshlayout.finishRefresh(false);
                    refreshlayout.finishLoadmore(false);
                }
            }
        });

    }

    private void initOldData(final RefreshLayout refreshlayout) {

        String year = et_year.getText().toString();
        String status = MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetAllWaterPointStatus(), 0, tv_status.getText().toString());
        String reason = MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetAllReasonList(), 0, tv_reason.getText().toString());


        String ApiUrl = Config.host
                + WebApi.Api_HistoryWaterPoint
                + "?limit=" + Config.PAGE_LIMIT
                + "&year=" + year
                + "&status=" + status
                + "&WarningID=" + reason;

        DataModel.GetApiRequestMode("WaterPointBean", ApiUrl, new InitDataBeanBack<WaterPointBean>() {
            @Override
            public void callbak(boolean b, List<WaterPointBean> list, String msg) {
                if (b) {
                    waterlist = list;
                    mAdapter.setNewData(list);
                    MarkWaterPoint(list);
                    refreshlayout.finishRefresh(true);//刷新完成
                    refreshlayout.finishLoadmore(true);
                    String[] nubber_arr =  ComputeTools.StatisticsWaterNumber(list);
                    water_tj_a.setText(nubber_arr[0]);
                    water_tj_b.setText(nubber_arr[1]);
                    water_tj_c.setText(nubber_arr[2]);
                    water_tj_d.setText(nubber_arr[3]);
                    water_tj_e.setText(nubber_arr[4]);
                    water_tj_f.setText(nubber_arr[5]);
                } else {
                    ToastShow(msg);
                    refreshlayout.finishRefresh(false);
                    refreshlayout.finishLoadmore(false);
                }
            }
        });
    }




    /**
     * ===============================================
     * 创建时间：2019/3/12 15:00
     * 编 写 人：ShenC
     * 方法说明：标记获取的积水点位置
     * ================================================
     * 修改内容：      修改时间：      修改人：
     * ===============================================
     */
    private void MarkWaterPoint(final List<WaterPointBean> list) {
        gWaterLayer.removeAll();
        mLocationMapList.clear();

        for (WaterPointBean m : list) {
            addwaterpoint(m);
        }
    }

    //添加点
    private void addwaterpoint(final WaterPointBean bean) {
        int icon = R.mipmap.jsd_gray;

        Point mapPoint = new  Point(bean.getX(), bean.getY());

        if(bean.getIsDelete().equals("Y")){
            icon = R.mipmap.jsd_gray;
        }else if(bean.getIsDelete().equals("N")){
            if(MyTextUtils.IsString(bean.getType()).equals("1")){
                icon = R.mipmap.jsd_yyd;
            }else if(MyTextUtils.IsString(bean.getType()).equals("2")){
                icon = R.mipmap.jsd_jsd;
            }
        }else if(bean.getIsDelete().equals("S")) {
            if (bean.getStatus().equals("0")) {
                icon = R.mipmap.jsd_r;
            } else if (bean.getStatus().equals("1")) {
                icon = R.mipmap.jsd_y;
            } else if (bean.getStatus().equals("2")) {
                icon = R.mipmap.jsd_green;
            }
        }

        PictureMarkerSymbol locationSymbol  = new PictureMarkerSymbol(mContext.getResources().getDrawable(icon));
        Graphic graphic = new Graphic(mapPoint, locationSymbol);

        if (IsLable) {
            PictureMarkerSymbol markerSymbol = new PictureMarkerSymbol(MapUtils.createMapBitMap(context, bean.getLocation()));
            Graphic graphictext = new Graphic(mapPoint, markerSymbol);
            markerSymbol.setOffsetY(-23);
            mLocationMapList.put(gWaterLayer.addGraphic(graphictext), bean);
        }
        mLocationMapList.put(gWaterLayer.addGraphic(graphic), bean);

    }

    private void chooseDeviceCode(final List<ProvinceBean> items, final int pos) {
        OptionsPickerView.Builder builder = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String itemName = items.get(options1).getPickerViewText();
                switch (pos) {
                    case 1:
                        tv_status.setText(itemName);
                        break;
                    case 2:
                        tv_reason.setText(itemName);
                        break;
                }
            }
        });
        OptionsPickerView<ProvinceBean> pickerView = new OptionsPickerView<>(builder);
        pickerView.setPicker(items);
        pickerView.show();
    }


    //退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            return super.onKeyDown(keyCode, event);
        }else{
            return  false;
        }
    }


}
